package com.drd.dt.back.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.drd.dt.back.dao.JGPushMapper;
import com.drd.dt.back.dto.JGPushDTO;
import com.drd.dt.back.entity.MessageActivity;
import com.drd.dt.back.service.JGPushService;
import com.drd.dt.common.Constant;
import com.drd.dt.common.SuccessResultEnum;
import com.drd.dt.common.tips.Tip;
import com.drd.dt.exception.BizExceptionEnum;
import com.drd.dt.exception.BussinessException;
import com.drd.dt.util.JgPushUtil;
import com.drd.dt.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class JGPushServiceImpl extends ServiceImpl<JGPushMapper, MessageActivity> implements JGPushService {

    private final Logger log = LoggerFactory.getLogger(this.getClass());
    private String pushUrl = "https://api.jpush.cn/v3/push";
    private boolean apns_production = true;//ios  true生产环境，false为开发环境
    private int time_to_live = 86400;

    @Autowired
    private JGPushMapper pushMapper;

    /**
     * 消息推送(推送所有人)
     *
     * @return
     */
    @Override
    public Tip pushMsg(JGPushDTO push) throws Exception {
        String alias = "all";//声明别名(广播，通知所有用户)
        Integer push_type = push.getPush_type();//5单品详情不入库
        String goods_id = push.getGoods_id();
        Integer is_login = push.getIs_login();
        Integer type = push.getType();
        String title = push.getTitle();
        String content = push.getContent();
        if (push_type == 1){//单品
            push = new JGPushDTO();
            push.setJump_action(3);
            push.setGoods_id(goods_id);
            push.setType(type);
            push.setIs_login(is_login);
            push.setTitle(title);
            push.setContent(content);
        }else if (push_type == 2){//活动
            push.setJump_action(4);
        }
        try {
            //获取极光的appkey和secret
            Map jg = pushMapper.getJgInfo();
            String appKey = jg.get("jg_app_key").toString();
            String masterSecret = jg.get("jg_app_secret").toString();
//            String appKey = "854b11c346afbecf7f70fec6";
//            String masterSecret = "97047b65df072eaa43d6c007";
            //ios使用券巴士的极光
            String ios_appKey = Constant.QBS_JG_APPKEY;
            String ios_masterSecret = Constant.QBS_JG_APPSECRET;
            String android_result = push(pushUrl, alias, push, appKey, masterSecret, apns_production, time_to_live);
            String ios_result = push(pushUrl, alias, push, ios_appKey, ios_masterSecret, apns_production, time_to_live);

            JSONObject android_resData = JSON.parseObject(android_result);
            JSONObject ios_resData = JSON.parseObject(ios_result);
            if (android_resData.containsKey("error") && ios_resData.containsKey("error")) {
                log.info("【极光推送信息失败！】");
                JSONObject error = JSON.parseObject(android_resData.getString("error"));
                log.info("错误信息为：" + error.get("message").toString());
            } else {
                log.info("【信息推送成功！】");
                if (push_type != 1){
                    MessageActivity activity = new MessageActivity();
                    BeanUtils.copyProperties(push,activity);
                    activity.setCreate_time(Constant.y_M_d_H_m_s.format(new Date()));
                    pushMapper.insert(activity);
                }
            }
        } catch (Exception e) {
            log.error("信息推送失败！", e);
        }

        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage());
    }

    /**
     * 组装极光推送专用json串
     */
    public static JSONObject generateJson(String alias, JGPushDTO push, boolean apns_production, int time_to_live) {
        JSONObject json = new JSONObject();
        JSONArray platform = new JSONArray();//平台
        platform.add("android");
        platform.add("ios");

        JSONObject notification = new JSONObject();//通知内容
        JSONObject android = new JSONObject();//android通知内容
        android.put("title", push.getTitle());
        android.put("alert", push.getContent());
        android.put("builder_id", 1);
        JSONObject android_extras = new JSONObject();//android额外参数
        android_extras.put("choose", "push");
        android_extras.put("data", push);
        android.put("extras", android_extras);

        JSONObject ios = new JSONObject();//ios通知内容
        JSONObject content = new JSONObject();//放ios标题和内容
        content.put("title",push.getTitle());
        content.put("body",push.getContent());
        ios.put("alert", content);
        ios.put("sound", "default");
        ios.put("badge", "+1");
        JSONObject ios_extras = new JSONObject();//ios额外参数
        ios_extras.put("choose", "push");
        ios_extras.put("jump_action", push.getJump_action());
        ios_extras.put("is_login", push.getIs_login());
        ios_extras.put("type", push.getType());
        ios_extras.put("jump_url", push.getJump_url());
        ios_extras.put("is_need_userid", push.getIs_need_userid());
        ios_extras.put("jump_type", push.getJump_type());
        ios_extras.put("discern_id", push.getDiscern_id());
        ios_extras.put("goods_id", push.getGoods_id());
        ios.put("extras", ios_extras);

        notification.put("android", android);
        notification.put("ios", ios);

        JSONObject options = new JSONObject();//设置参数
        options.put("time_to_live", Integer.valueOf(time_to_live));
        options.put("apns_production", apns_production);

        json.put("platform", platform);
        json.put("audience", alias);
        json.put("notification", notification);
        json.put("options", options);
        return json;
    }

    /**
     * 推送方法-调用极光API
     */
    public static String push(String reqUrl, String alias, JGPushDTO push, String appKey, String masterSecret, boolean apns_production, int time_to_live) {
        String base64_auth_string = JgPushUtil.encryptBASE64(appKey + ":" + masterSecret);
        String authorization = "Basic " + base64_auth_string;
        return JgPushUtil.sendPostRequest(reqUrl, generateJson(alias, push, apns_production, time_to_live).toString(), "UTF-8", authorization);
    }


    /**
     * 推送活动的列表
     */
    @Override
    public Tip pushList(int page, int size) {
        Page pa = new Page(page,size);
        List<MessageActivity> list =  pushMapper.selectMessageActivity(pa,new HashMap<>());
        pa.setRecords(list);
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(),list);
    }

    /**
     * 详情
     */
    @Override
    public Tip detail(Integer id) {
        MessageActivity activity = pushMapper.selectById(id);
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(),activity);
    }

    /**
     * 更新
     */
    @Override
    public Tip update(JGPushDTO pushDTO) {
        MessageActivity activity = new MessageActivity();
        BeanUtils.copyProperties(pushDTO,activity);
        pushMapper.updateById(activity);
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage());
    }

    /**
     * 删除
     */
    @Override
    public Tip delete(Integer id) {
        pushMapper.deleteById(id);
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage());
    }
}
